﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dicom.Network.Client;
using Dicom.Network;
using Dicom.Data;
using System.Threading;
using DicomScu.Scu;
using DicomScu;

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ScuConfigDestinationCollection distinatination = new ScuConfigDestinationCollection();
        ScuConfig config = new ScuConfig();
        private void Form1_Load(object sender, EventArgs e)
        {
            button4.Enabled = false;
            btxmove_series.Enabled = false;
            config.LocalAE = "localhost";
            config.RemoteAE = "testae";
            config.RemoteHost = "10.0.0.185";
            config.RemotePort = 6789;
            distinatination.ConfigCollection.Add(config);
            distinatination.LocalConfig = config;
            distinatination.LocalStoreDirectoryConfig = @"D:\test";
            DicomServerHandler.LocalStoreDirectoryConfig = distinatination.LocalStoreDirectoryConfig;
            DicomServerHandler.StartListenning(distinatination.LocalConfig);
            btxtfind.Enabled = false;
        }
       public CFindStudyQuery studychuyen=new CFindStudyQuery();
       private themvaolistview_delegate themvaolistview_add1;
        private void button1_Click(object sender, EventArgs e)
        {
            
            listBox1.Items.Clear();
            string msg = "";
            CEchoClient client = new CEchoClient();
            client.CalledAE = "CONQUESTSRV1";
            client.CallingAE = "CONQUESTSRV1";
            client.ConnectTimeout = 20;
            client.DimseTimeout = 20;
            client.MaxPduSize = Convert.ToUInt16(29);
            client.Priority = DcmPriority.High;
            client.OnCEchoResponse += delegate(byte presentationID, ushort messageID, DcmStatus status)
            {
                msg = status.Description;
            };
            client.Connect("127.0.0.1",5678, DcmSocketType.TCP);
            if (client.Wait()==true)
            {
                listBox1.Items.Add(msg);
                btxtfind.Enabled = true;

            }
            else
            {
                listBox1.Items.Add("error");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        { 
           
            listView1.Items.Clear();
            
            CFindClient client=new CFindClient();
            client.CalledAE = "CONQUESTSRV1";
            client.CallingAE = "CONQUESTSRV1";
            
            client.ConnectTimeout = 20;
            client.DimseTimeout = 20;
            client.MaxPduSize = Convert.ToUInt16(29);
            client.SocketTimeout = 30;
            client.Priority = DcmPriority.High;
           ThreadPool.QueueUserWorkItem(new WaitCallback(connect),client);
         
            CFindStudyQuery query = new CFindStudyQuery();
            query.PatientID = null;
            query.PatientsName = null;
            query.AccessionNumber = null;
            DcmDataset data = query.ToDataset(DcmTS.DeflatedExplicitVRLittleEndian);
            client.OnCFindResponse = delegate(DcmDataset querys, DcmDataset result)
            {
               
                laythongtin(result);

            };
            client.AddQuery(data);
           
            
               
           

           
            
        }
        //public List<PatientInfo> list = new List<PatientInfo>();
        private void laythongtin(DcmDataset result)
        {
            
            CFindStudyQuery thongtin = new CFindStudyQuery();
            thongtin.AccessionNumber = getthongtin_bytab(result, DcmTags.AccessionNumber);
            thongtin.ModalitiesInStudy = getthongtin_bytab(result, DcmTags.ModalitiesInStudy);
            thongtin.PatientID = getthongtin_bytab(result, DcmTags.PatientID);
            thongtin.PatientsName = getthongtin_bytab(result, DcmTags.PatientsName);
          

            thongtin.StudyDescription = getthongtin_bytab(result, DcmTags.StudyDescription);
            thongtin.StudyID = getthongtin_bytab(result, DcmTags.StudyID);
            thongtin.StudyInstanceUID = getthongtin_bytab(result, DcmTags.StudyInstanceUID);
            
            
            
            
                try
                {
                    addtolistview(thongtin);
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            
           
        }
        public delegate  void invokelistview(CFindStudyQuery infor);
        private void addtolistview(CFindStudyQuery infomation)
        {
           if (listView1.InvokeRequired==true)
           {
               invokelistview invoke = new invokelistview(kiemtra);
               this.Invoke(invoke,new object[]{infomation});
           }

           
        }
        private void kiemtra(CFindStudyQuery patient)
        {
           // listView1.Items.Clear();
            
            ListViewItem item = new ListViewItem(patient.PatientID);
            item.SubItems.Add(patient.PatientsName);
            item.SubItems.Add(patient.StudyInstanceUID);
            item.Tag = patient;
            
            listView1.Items.Add(item);
           
        }
        private string getthongtin_bytab(DcmDataset dcmdataset, DcmTag dcmtag)
        {
            DcmElement element = dcmdataset.GetElement(dcmtag);
            if (element.GetValueString()!=null)
            {
                return element.GetValueString();
            }
            else
            {
                return "";
            }
        }
        private void connect(object s)
        {
            CFindClient client =(CFindClient)s;
           
            client.Connect("127.0.0.1", 5678, DcmSocketType.TCP);
            
           
            if (client.Wait()==true)
{
// MessageBox.Show("error");

            }
        }
       
       
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                button4.Enabled = true;
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    listView2.Items.Clear();
                    studychuyen = (CFindStudyQuery)item.Tag;
                    CFindClient client = new CFindClient();
                    client.CallingAE = "CONQUESTSRV1";
                    client.CalledAE = "CONQUESTSRV1";
                    client.ConnectTimeout = 10;
                    client.MaxPduSize = Convert.ToUInt16(29);
                    client.SocketTimeout = 20;
                    client.Priority = DcmPriority.High;
                    CFindSeriesQuery ht = new CFindSeriesQuery();
                    ht.StudyInstanceUID = studychuyen.StudyInstanceUID;
                    ThreadPool.QueueUserWorkItem(new WaitCallback(connect), client);
                    DcmDataset series = ht.ToDataset(DcmTS.DeflatedExplicitVRLittleEndian);
                    client.AddQuery(series);
                   
                    client.OnCFindResponse = delegate(DcmDataset query, DcmDataset result)
                    {
                        themvaolistview(result);
                    };
                }
            }
            else
            {
                button4.Enabled = false;
            }
        }

        private void themvaolistview(DcmDataset result)
        {
            CFindSeriesQuery client = new CFindSeriesQuery();
            client.SeriesInstanceUID = them(DcmTags.SeriesInstanceUID, result);
            client.SeriesDescription = them(DcmTags.SeriesDescription, result);
            client.Modality = them(DcmTags.Modality, result);
            client.SeriesNumber = them(DcmTags.SeriesNumber, result);
            client.SeriesTime = them(DcmTags.SeriesTime, result);
            themvaolistview2(client);
        }
        public delegate void themvaolistview_delegate(CFindSeriesQuery client);
        private void themvaolistview2(CFindSeriesQuery client)
        {
            if (listView2.InvokeRequired == true)
            {
                themvaolistview_delegate ht = new themvaolistview_delegate(them_listview);
                this.Invoke(ht,new object[]{client});

            }

        }
        private void them_listview(CFindSeriesQuery client)
        {
            ListViewItem item = new ListViewItem(client.SeriesInstanceUID);
            //item.SubItems.Add("sdsdsd");
            item.Tag = client;
            listView2.Items.Add(item);
        }
#region them
        private string them(DcmTag dcmTag, DcmDataset query)
        {
            DcmElement element = query.GetElement(dcmTag);
            if (element.GetValueString() == null)
            {
                return "";
            }
            else
            {
                return element.GetValueString();
            }
        }
#endregion
       

        private void button3_Click(object sender, EventArgs e)
        {
            cstore ht = new cstore();
            ht.ShowDialog();
           // this.Close();
           
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                CMoveClient client = new CMoveClient();
                client.CalledAE = "LYNXPACS";
                client.CallingAE = "testae";
                client.ConnectTimeout = 10;
                client.MaxPduSize = Convert.ToUInt16(30);
                client.SocketTimeout = 30;
                client.Priority = DcmPriority.High;
                client.DestinationAE = "testae";
               
                
                client.AddQuery(DcmQueryRetrieveLevel.Study, studychuyen.StudyInstanceUID);
                client.OnCMoveResponse = delegate(CMoveQuery querys, DcmDataset dataset, DcmStatus status, ushort remain, ushort complete, ushort warning, ushort failure)
                {
                    thongbao(status.Description);
                };
                ThreadPool.QueueUserWorkItem(new WaitCallback(connect_move), client);
            }
            catch(Exception ex)
            {
                throw ex;
            }
            
        }
        public delegate void thongbaotest(string chuoi);
        private void thongbao(string p)
        {
            // throw new NotImplementedException();

            if (listBox1.InvokeRequired == true)
            {
                thongbaotest test = new thongbaotest(chuoihienthi);
                Invoke(test, new object[] { p });
            }
        }
        private void chuoihienthi(string chuoi)
        {
            listBox1.Items.Add(chuoi);
        }
        private void connect_move(object s)
        {
            CMoveClient client = (CMoveClient)s;
            client.Connect("127.0.0.1", 5678, DcmSocketType.TCP);
        }


        public themvaolistview_delegate themvaolistview_add { get; set; }
       public CFindSeriesQuery query=new CFindSeriesQuery();
        private void listView2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView2.SelectedItems.Count > 0)
            {
                btxmove_series.Enabled = true;
                foreach (ListViewItem item in listView2.SelectedItems)
                {
                    query = (CFindSeriesQuery)item.Tag;
                }

            }
            else
            {
                btxmove_series.Enabled = false;
            }
        }

        private void btxmove_series_Click(object sender, EventArgs e)
        {
            try
            {
               
                CMoveClient client = new CMoveClient();
                client.CalledAE = "CONQUESTSRV1";
                client.CallingAE = "CONQUESTSRV1";
                client.ConnectTimeout = 10;
                client.MaxPduSize = Convert.ToUInt16(30);
                client.SocketTimeout = 30;
                client.Priority = DcmPriority.High;
                client.DestinationAE = "CONQUETSTSRV1";


                client.AddQuery(DcmQueryRetrieveLevel.Series, query.SeriesInstanceUID);
                client.OnCMoveResponse = delegate(CMoveQuery querys, DcmDataset dataset, DcmStatus status, ushort remain, ushort complete, ushort warning, ushort failure)
                {
                    thongbao(status.Description);
                };
                ThreadPool.QueueUserWorkItem(new WaitCallback(connect_move), client);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
